import { Button, Col, Modal, Row, Space, Steps } from "antd";
import React, { MutableRefObject, useCallback, useMemo, useRef, useState } from "react";
import step1 from "./step1";
import Step2 from "./step2";
import step3 from "./step3";
import Step4 from "./step4";

interface AddModalProps {
  /** 点击确定回调 */
  onAddModalOk: (data: any[]) => void;
  /** 点击模态框右上角叉、取消按钮、Props.maskClosable 值为 true 时的遮罩层或键盘按下 Esc 时的回调 */
  onAddModalCancel: () => void;
}

export interface StepProps {
  data: any[]
  onStepDataUpdated: (value: any) => {}
  validator: MutableRefObject<() => Promise<{}>>
}

const contents: any[] = [step1, Step2, step3, Step4];
const data: any[] = [null, null, null, null];

const AddTaskModal: React.FC<AddModalProps> = ({ onAddModalOk, onAddModalCancel }) => {
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [isDataValid, setIsDataValid] = useState<boolean>(false);
  const validator = useRef<() => Promise<any>>();
  const nextButtonLabel = useMemo(() => currentStep < 3 ? "下一步" : "完成", [currentStep]);
  const Content = useMemo(() => contents[currentStep], [currentStep]);

  const handleClickCancel = useCallback(() => onAddModalCancel(), [onAddModalCancel]);
  const handleClickLast = useCallback(() => setCurrentStep(currentStep - 1), [currentStep]);
  const handleClickNext = useCallback(async () => {
    if (currentStep < 3) {
      setCurrentStep(currentStep + 1);
    } else if (validator.current) {
      data[currentStep] = await validator.current();
      onAddModalOk([...data]);
    }
  }, [currentStep, onAddModalOk]);

  const handleStepDataUpdated = useCallback((item: any) => {
    data[currentStep] = item;
    setIsDataValid(item != null);
  }, [currentStep]);

  return (
    <Modal okText="下一步" width="80%" centered
      title="新建任务" visible={true}
      onCancel={handleClickCancel} bodyStyle={{ height: "75vh", overflow: "auto" }}
      footer={
        <Space>
          <Button type="default" onClick={handleClickCancel}>取消</Button>
          <Button type="default" disabled={currentStep === 0} onClick={handleClickLast}>上一步</Button>
          <Button type="primary" disabled={!isDataValid} onClick={handleClickNext}>{nextButtonLabel}</Button>
        </Space>
      }>
      <Row gutter={24}>
        <Col push={2} span={20}>
          <Steps current={currentStep} style={{ margin: "16px auto 32px auto" }}>
            <Steps.Step title="上传任务模板" />
            <Steps.Step title="设置任务参数" />
            <Steps.Step title="设置任务调度" />
            <Steps.Step title="保存任务配置" />
          </Steps>
        </Col>
        <Col span={24}>
          <Content onStepDataUpdated={handleStepDataUpdated} data={data} validator={validator} />
        </Col>
      </Row>
    </Modal>
  )
};

export default AddTaskModal;
